﻿using Microsoft.AspNetCore.Http;
using System.Threading.Tasks;

namespace Plasp.WebScoketServer.Web.WebSocketProvider
{
    public class WebSocketMiddleware
    {
        private readonly RequestDelegate _next;
        private readonly WebSocketHandler _webSocketHandler;
        public WebSocketMiddleware(WebSocketHandler webSocketHandler, RequestDelegate next) {
            _webSocketHandler = webSocketHandler;
            _next = next;
        }

        /// <summary>
        /// 接收到一次请求
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public async Task InvokeAsync(HttpContext context) {
            if (!context.WebSockets.IsWebSocketRequest)
                await _next.Invoke(context);

            var socket = await context.WebSockets.AcceptWebSocketAsync();
            await _webSocketHandler.OnConnected(socket);
            await _webSocketHandler.HandlerProcessAsync(socket); //处理请求
        }
    }
}
